import {
  getToken,
  setToken,
  removeToken,
  setCsrfToken,
  removeCsrfToken,
} from "@/utils/auth";
import _ from "lodash";
import request from "@/utils/request";

const user = {
  state: {
    token: getToken(),
    name: "",
    userId: "",
    avatar: "",
    roles: [],
    permissions: [],
    autoTriggerGuideUser: [],
    manualTriggerGuideUser: [],
    profile: {},
    lastLoginDate: "",
    lastLoginIp: "",
    loginId: "",
    userType: "",
    departmentId: "",
    departmentName: "",
    department: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_CSRF_TOKEN: (state, csrfToken) => {
      state.csrfToken = csrfToken;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_AUTO_TRIGGER_USER_GUIDE: (state, autoTriggerGuideUser) => {
      state.autoTriggerGuideUser = autoTriggerGuideUser;
    },
    SET_MANUAL_TRIGGER_USER_GUIDE: (state, manualTriggerGuideUser) => {
      state.manualTriggerGuideUser = manualTriggerGuideUser;
    },
    SET_USER: (state, user) => {
      state.name = user.userName;
      state.userId = user.userId;
      state.profile = user.profile;
      state.lastLoginDate = user.lastLoginDate;
      state.lastLoginIp = user.lastLoginIp;
      state.loginId = user.loginId;
      state.departmentId = user.departmentId;
      state.departmentName = user.departmentName;
      state.userType = user.userType;
      state.department = user.department;
    },
  },

  actions: {
    // 登录
    Login({
      commit
    }, userInfo) {
      const {
        password,
        code,
        uuid,
        activationCode,
        activationTime,
        encryptor,
      } = userInfo;
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        request({
            url: "/account/apiLogin",
            method: "post",
            data: {
              code,
              uuid,
              activationCode,
              activationTime,
              principal: encryptor.encrypt(
                JSON.stringify({
                  username,
                  password,
                })
              ),
            },
          })
          .then((res) => {
            if (res.success) {
              setToken(res.parameters.authToken);
              setCsrfToken(res.parameters.csrfToken);
              commit("SET_TOKEN", res.parameters.authToken);
              commit("SET_CSRF_TOKEN", res.parameters.csrfToken);

              resolve();
            } else {
              reject(res.message);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        request({
            url: "/account/getUserInfo",
            method: "post",
          })
          .then((res) => {
            const user = res.parameters.user;
            const avatar =
              user.profile && user.profile.photoUrl ?
              `${process.env.VUE_APP_BASE_API}/attachment/down/${user.profile.photoUrl}` :
              require("@/assets/images/profile.png");

            const roles = res.parameters.roles || [];
            const permissions = res.parameters.permissions || [];
            commit("SET_ROLES", roles);
            commit(
              "SET_PERMISSIONS",
              _.isArray(permissions) ? permissions : [permissions]
            );

            commit("SET_USER", user);
            // commit("SET_NAME", user.userName);
            // commit("SET_USER_ID", user.userId);

            commit("SET_AVATAR", avatar);

            resolve({
              roles: roles,
            });
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        request({
            url: "/account/apiLogout",
            method: "post",
          })
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_CSRF_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            removeCsrfToken();

            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");

        removeToken();
        resolve();
      });
    },

    setAvatar({
      commit
    }, avatar) {
      commit("SET_AVATAR", avatar);
    },

    // 加载向导用户
    loadCurrNotTriggerGuide({
      commit
    }) {
      return new Promise((resolve, reject) => {
        request({
            url: "/system/guide/getCurrNotTriggerGuide",
            method: "get",
          })
          .then((guides) => {
            const manualTriggerGuideUser = [];
            const autoTriggerGuideUser = [];
            if (Array.isArray(guides)) {
              guides.forEach((item) => {
                if (item.triggerType === "auto") {
                  autoTriggerGuideUser.push(item);
                } else if (item.triggerType === "manual") {
                  manualTriggerGuideUser.push(item);
                }
              });
            }
            commit("SET_AUTO_TRIGGER_USER_GUIDE", autoTriggerGuideUser);
            commit("SET_MANUAL_TRIGGER_USER_GUIDE", manualTriggerGuideUser);
            resolve(guides);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
};

export default user;
